package com.bo.Controller;

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import com.bo.Entity.Company;
import com.bo.Service.CompanyService;
import com.bo.Validator.CompanyValidator;
import com.bo.Validator.UserValidator;

@Controller
@SessionAttributes("user")
public class LoginController {
	
	@Autowired
	private CompanyService companyService;
	
	@Autowired
	private UserValidator userValidator;
	
	@Autowired
	private CompanyValidator companyValidator;
	
	
	@RequestMapping(value="/login.do", method=RequestMethod.GET)
	public String login(Model model){

		
		model.addAttribute("user", new Company());
		
		return "login";
	}

	
	
	@RequestMapping(value="/login.do", method=RequestMethod.POST)
	public String login(@ModelAttribute("user") Company user,BindingResult result
			                                 ,SessionStatus status,HttpServletRequest request){
     
	
 	     userValidator.validate(user, result);
		
		
        if(result.hasErrors()){
        	return "login";
        
        }else{

        	Company company=companyService.login(user);
        	
        	if(company==null){
        		
        		userValidator.validateAccount(user.getAccount(), result);
        		
        		return "login";
        	
        	}else{
        		
        		status.setComplete();
        		
        		request.getSession().setAttribute("isLogin", true);
        		request.getSession().setAttribute("companyId", company.getId());
        		
        		return "redirect:/main/mainPage.do";

        	}
        }
	}


	@RequestMapping(value="/registerCompany.do", method=RequestMethod.GET)
	public String registerUser(Model model){

		model.addAttribute("company", new Company());

		return "registerCompany";
	}
	
	
	
	@RequestMapping(value="/registerCompany.do", method=RequestMethod.POST)
	public String registerUser(@ModelAttribute("company") Company company,BindingResult result){

		companyValidator.validate(company, result);
		
		if(result.hasErrors()){
			
			return "registerCompany";
			
		}else{
			
			companyValidator.validateAccount(company.getAccount(), result);
			
			if(result.hasErrors()){
				
				return "registerCompany";
			
			}else{
				
				companyService.save(company);
				
				return "registerSuccess";
				
    		}
		}
	}
	

}
